package win.zxshuo.www.schedule;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import win.zxshuo.www.model.BookModel;
import win.zxshuo.www.model.TargetUrlModel;
import win.zxshuo.www.model.chapters.ChapterModel;
import win.zxshuo.www.service.BookService;
import win.zxshuo.www.service.ChapterService;
import win.zxshuo.www.service.TargetUrlService;
import win.zxshuo.www.spider.BaiduSearch;
import win.zxshuo.www.spider.JieqiSpider;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component("tUpdateBooks")
@Scope("prototype")
public class ThreadUpdateBooks extends Thread {
    private Log logger = LogFactory.getLog(ThreadUpdateBooks.class);

    private List<BookModel> bookModels;

    public List<BookModel> getBookModels() {
        return bookModels;
    }

    public void setBookModels(List<BookModel> bookModels) {
        this.bookModels = bookModels;
    }

    @Autowired
    TargetUrlService targetUrlService;

    @Autowired
    BookService bookService;

    @Autowired
    ChapterService chapterService;

    @Autowired
    BaiduSearch baiduSearch;

    @Autowired
    JieqiSpider jieqiSpider;


    @Override
    public void run(){
        if (bookModels == null || bookModels.size()==0){
            logger.error("没有任何的book可以操作");
        }else {
            for (BookModel bookModel:bookModels){
                Set<TargetUrlModel> targetUrlModels = bookModel.getTargetUrlModels();
                if (targetUrlModels.size()<=0){
                    List<String> results = baiduSearch.getSearchResultList(bookModel.getName());
                    for (String url:results){
                        try {
                            Map<String,String> bookinfo = jieqiSpider.getBookinfo(jieqiSpider.getPageContent(url));
                            if (bookinfo.get("author").equals(bookModel.getAuthorModel().getName())&&bookinfo.get("title").equals(bookModel.getName())){
                                targetUrlService.addNew(bookModel,url);
                            }
                        }catch (Exception e){
                            logger.info("使用采集并获取书籍的目标采集url出错了，详情请看日志");
                            logger.error(e.getCause());
                            logger.error(e.getStackTrace());
                        }
                    }
                }
                targetUrlModels = bookModel.getTargetUrlModels();
                for (TargetUrlModel targetUrlModel:targetUrlModels){
                    if (targetUrlModel.getStatus() == 1){
                        try {
                            jieqiSpider.getBookIndex(targetUrlModel.getUrl(),bookModel);

                            break;
                        }catch (Exception e){
                            logger.info("失败了");
                            logger.error(e.getCause());
                            logger.error(e.getStackTrace());
                        }
                    }


                }


                // 根据书籍来，不是根据还剩余多少未采集的来。
                List<ChapterModel> chapterModels = chapterService.getBookUncrawlerUrl(bookModel);
                for (ChapterModel chapterModel:chapterModels){
                    // 这里让他睡1秒在继续采集，防止触发服务器的防采集机制
                    jieqiSpider.startCrawlerChapter(chapterModel,bookModel);
                    try{
                        Thread.sleep(1000);// 睡500毫秒，保证不会触发目标服务器的采集限制
                    }catch (Exception e){
                        logger.info("沉睡1秒失败了？？？一脸懵逼，连睡都不给睡？");
                        logger.error(e.getCause());
                        logger.error(e.getMessage());
                    }
                }
                try{
                    bookService.setBookCrawlerFinishedRecord(bookModel);
                }catch (Exception e){
                    logger.error(e.getCause());
                    logger.error(e.getStackTrace());
                    logger.info("更新书籍采集记录失败");
                }
            }
        }
    }

}
